﻿using System.Windows;
using System.Windows.Interactivity;

namespace Thinktecture.UIAnnotations.Behaviors
{
    public class CloseWindowBehavior : TriggerAction<FrameworkElement>
    {
        protected override void Invoke(object parameter)
        {
            bool dialogResultSet = false;
            var window = VisualTreeHelpers.GetRootElement(this.AssociatedObject);
            if (window != null)
            {
                // set the DialogResult property
                var resultProp = window.GetType().GetProperty("DialogResult");
                if (resultProp != null)
                {
                    var dialogResult = this.DialogResult;
                    try
                    {
                        resultProp.SetValue(window, dialogResult, new object[] { });
                        dialogResultSet = true;
                    }
                    catch { }
                }

                // close the window
                var closeMethod = window.GetType().GetMethod("Close");
                if (dialogResultSet == false && closeMethod != null)
                {
                    closeMethod.Invoke(window, new object[] { });
                }
            }
        }
        
        #region DialogResult

        public static readonly DependencyProperty DialogResultProperty =
            DependencyProperty.Register("DialogResult", typeof(bool?), typeof(CloseWindowBehavior), new PropertyMetadata(null));
        public bool? DialogResult { get { return (bool?)GetValue(DialogResultProperty); } set { SetValue(DialogResultProperty, value); } }

        #endregion
        
    }
}
